#include "MyTextItem.h"
#include <QPainter>
#include <QEvent>
#include <QKeyEvent>
#include <QFont>
#include <QTextDocument>
#include <QTextCursor>

namespace QtTutorial5
{
	/**
	* Constructor
	*/
	MyTextItem::MyTextItem(QGraphicsItem* inParent) :
		QGraphicsTextItem(inParent),
		mTextSelected(false)
	{
		setTextInteractionFlags(Qt::TextEditorInteraction);
		setFlag(QGraphicsItem::ItemIsFocusable);
		this->setFont(QFont("Arial",14,-1,false));
		this->setFocus(Qt::MouseFocusReason);
	}

	/**
	* Constructor
	* \param inText Value of the text that needs to be displayed
	* \param inParent Parent widget's pointer
	*/
	MyTextItem::MyTextItem(const QString& inText, QGraphicsItem* inParent) :
		QGraphicsTextItem(inText, inParent),
		mTextSelected(false)
	{
		setTextInteractionFlags(Qt::TextEditorInteraction);
		setFlag(QGraphicsItem::ItemIsFocusable);
		this->setFont(QFont("Arial", 14, -1, false));
		this->setFocus(Qt::MouseFocusReason);
	}

	/**
	* Destructor
	*/
	MyTextItem::~MyTextItem()
	{
	}

	/**
	* Handles the key press event from the keyboard
	* \param event contains event information
	*/
	void MyTextItem::keyPressEvent( QKeyEvent *event )
	{		
		QGraphicsTextItem::keyPressEvent(event);
	}

	/**
	* Handles the key release event from the keyboard
	* \param event contains event information
	*/
	void MyTextItem::keyReleaseEvent( QKeyEvent *event )
	{
		QGraphicsTextItem::keyReleaseEvent(event);
	}

	/**
	* Handles events
	* \param inEvent containts event information
	*/
	bool MyTextItem::event( QEvent *inEvent )
	{
		// handle events only if this text widget has focus
		if(this->hasFocus() && inEvent->type() == QEvent::KeyPress)
		{
			QKeyEvent* keyEvent = reinterpret_cast<QKeyEvent*>(inEvent);
			keyPressEvent(keyEvent);
			return true;
		}
		return QGraphicsTextItem::event(inEvent);
	}
}